package com.hfzy.ihk.web.ivr.biz;

import com.hfzy.ihk.common.facade.enums.call.CommitTo;
import com.hfzy.ihk.common.util.ValidateUtils;
import com.hfzy.ihk.common.util.date.DateUtils;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.facade.ivr.enums.MainCallTypeEnum;
import com.hfzy.ihk.facade.ivr.vo.CallHistory;
import com.hfzy.ihk.web.ivr.constant.Constants;
import com.hfzy.ihk.web.ivr.constant.RedisKey;
import com.hfzy.ihk.web.ivr.support.SampleMemoryCache;
import com.hfzy.ihk.web.ivr.support.SelectShowNumSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/4/29.
 * @author wws
 * 点击拨号业务逻辑
 */
@Component("clickCallBiz")
@Lazy
public class ClickCallBiz {

    @Autowired
    RedisTemplate redisTemplate;
    //freeswitch外呼业务逻辑
    @Autowired
    private FreeswitchAsrCallOutBiz freeswitchAsrCallOutBiz;

    @Autowired
    SelectShowNumSupport selectShowNum;

    @Value("${spring.profiles.active}")
    private String profiles;
    private static final Logger logger = LoggerFactory.getLogger(ClickCallBiz.class);



    /**
     * 单呼呼出
     * @return 正常情况下：返回null
     * */
    public Map<String,String> handleClickCallWebSocket( String mainCallPhone,String machineFrom ,
                                                          String createUserId ,String createUserNo,String dataId  ,String whereFrom ,String pageFrom ,
                                                          String mainCallType ,String commitTo , String city, String customerName,
                                                        String project,String propertyNo,String objectId,String sessionId,
                                                        String callTaskId,String packageId,String packageName,String voiceCode,String voiceText) {
        Map<String, String> validateMap;
        CallHistory callHistory = new CallHistory();

        if(StringUtil.isNotNull(commitTo)){ //不为空就使用该线路 这个一般前端控制
            callHistory.setCommitTo(Integer.valueOf(commitTo));
        }else{
            callHistory.setCommitTo(13);
        }
        try {

            validateMap = validateClickCallWebSocket(mainCallPhone, machineFrom,
                    String.valueOf(createUserId), String.valueOf(dataId), String.valueOf(whereFrom),
                    String.valueOf(pageFrom), String.valueOf(mainCallType), customerName,sessionId,callTaskId,packageId);


            if (validateMap !=null && Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION.equals(validateMap.get(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE))) {
                return validateMap;
            }


            //获取主显号码
            if(CommitTo.ASR_FREESWITCH.getValue().equals(commitTo)) { //目前默认联通线路
                String copShowNum = selectShowNum.getCopShowNum(city);
                logger.info(">>>get copShowNum:{},sessionId:{}",copShowNum.toString(),sessionId);
                if(copShowNum==null){
                    validateMap = new HashMap<>(6);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_16);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);
                    return validateMap;
                }
                callHistory.setShowNum(copShowNum);
            }


            if(StringUtil.isEmpty(dataId))
                callHistory.setDataId("-1");
            else
                callHistory.setDataId(dataId);

            callHistory.setSessionId(sessionId);

            callHistory.setMainCallPhone(mainCallPhone);
            callHistory.setMachineFrom(machineFrom);
            callHistory.setWhereFrom(Integer.valueOf(whereFrom));
            callHistory.setPageFrom(Integer.valueOf(StringTools.notSetValue(pageFrom,"-1")));

            //* mainCallPhone:客户号码。
            callHistory.setMainCallType(MainCallTypeEnum.MAIN_CALL_PHONE_IS_CUSTOMER.getValue());

            callHistory.setCreateUserId(StringTools.notSetValue(createUserId,"-1"));
            callHistory.setCreateUserNo(StringTools.notSetValue(createUserNo,"-1"));
            callHistory.setCity(Integer.valueOf(StringTools.notSetValue(city,"-1")));

            callHistory.setCustomerName(StringTools.notSetValue(customerName,"-1"));//客户名称

            callHistory.setCallType(0);//通话类型：呼出(0)、呼入(1)
            callHistory.setCreateTime(new Date());
            callHistory.setProject(StringTools.notSetValue(project,"-1"));
            callHistory.setPropertyNo(StringTools.notSetValue(propertyNo,"-1"));
            callHistory.setObjectId(StringTools.notSetValue(objectId,"-1"));
            callHistory.setCallTaskId(StringTools.notSetValue(callTaskId,"-1"));
            callHistory.setPackageId(StringTools.notSetValue(packageId,"-1"));
            callHistory.setPackageName(StringTools.notSetValue(packageName,"-1"));
            callHistory.setVoiceCode(voiceCode);
            callHistory.setVoiceText(voiceText);

            freeswitchAsrCallOutBiz.todoCallOut(callHistory);

        } catch (Exception e) {

            logger.error("ivr ->>>>呼叫异常",e);

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_3);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);

            logger.error("ivr webSocketListener exception:", e);
        }

        return validateMap;
    }


    /**
     * 验证从websocket呼出 单呼
     * @return 正常情况下：返回null
     * */
    public Map<String,String> validateClickCallWebSocket( String mainCallPhone,String machineFrom ,
                                                String createUserId ,String dataId  ,String whereFrom ,String pageFrom ,
                                                String mainCallType ,String customerName,String sessionId,String callTaskId,String packageId ) {
        if("11".equals(whereFrom)||"25".equals(whereFrom)) //用于保利测试的不判断,用于crm freeswitch测试的不判断
            return null;

        Map<String, String> validateMap = null;

        if (SampleMemoryCache.isBadCustomerPhone(mainCallPhone)) {

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_12);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);

            return validateMap;
        }

        if( mainCallPhone == null || //主叫；由拨号时发送过来
            machineFrom == null ||//机器码：用于定位websocket对象（websocket）
            createUserId == null ||
            whereFrom == null || //来源：app(0),置业(1)
            pageFrom == null || //app盘源(0),app联动call(1),置业盘源(2)，置业联动call(3)? （websocket）
            callTaskId == null || customerName == null||packageId==null){

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_4);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);
            return validateMap;
        }

        if(!ValidateUtils.isNumeric(mainCallPhone)) {

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_2_2);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);

            return validateMap;
        }

        if (!ValidateUtils.isNumeric(whereFrom) ||
                !ValidateUtils.isNumeric(mainCallType)) {

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_2);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);

            return validateMap;
        }

        //判断是否有呼出超出了限制
        try {
            if(pageFrom!=null&&("1".equals(pageFrom)||"3".equals(pageFrom)||"10".equals(pageFrom))) {
                Object count = redisTemplate.opsForHash().get(RedisKey.TODAY_CALL_COUT, mainCallPhone);
                if (count != null && Integer.valueOf(count.toString()) > 0) {
                    //判断当天是否对该号码呼叫次数超过一次
                    validateMap = new HashMap<>(6);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_333);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);
                    return validateMap;
                }
            }

        }catch (Exception e){
            logger.error("ivr >>查询呼叫次数异常",e);
        }
        return validateMap;
    }


}
